import * as cheerio from 'cheerio'

export interface TdabsParsedInfo {
  reference_number?: string
  applicant_name_masked?: string
  id_number_masked?: string
  license_number_masked?: string
  appointment_date?: string // YYYY-MM-DD
  appointment_date_dmy?: string // DD-MM-YYYY（与预约管理字段一致）
  appointment_time?: string // HH:MM（24小时制）
  appointment_datetime?: string
  appointment_datetime_text?: string
  office?: string
  office_display?: string
  service_type_text?: string
  email_masked?: string
  phone_masked?: string
  extras?: Array<{ label: string, value: string }>
}

function toDMY(ymd?: string): string | undefined {
  if (!ymd)
    return undefined
  const m = ymd.match(/^(\d{4})-(\d{2})-(\d{2})$/)
  if (!m)
    return undefined
  return `${m[3]}-${m[2]}-${m[1]}`
}

export function parseAppointmentInfo(html: string): { success: boolean, data?: TdabsParsedInfo, error?: string } {
  try {
    const $ = cheerio.load(html)
    const data: TdabsParsedInfo = {}
    const extras: Array<{ label: string, value: string }> = []

    // 参考编号（页面上通常有空格/连字符）
    const refText = $('body').text()
    const refMatch = refText.match(/(參考編號|参考编号)[：:\s]*([A-Z0-9\s-]{6,})/i)
    if (refMatch) {
      data.reference_number = (refMatch[2] || '').replace(/\s|-/g, '')
    }

    $('tr').each((_, row) => {
      const cells = $(row).find('td, th')
      if (cells.length < 2)
        return
      const label = $(cells[0]).text().replace(/\s+/g, ' ').trim()
      const value = $(cells[1]).text().replace(/\s+/g, ' ').trim()
      if (!label || !value)
        return

      if (/護照號碼|香港身分證號碼|身份证|護照|证件/.test(label)) {
        data.id_number_masked = value
      }
      else if (/姓名/.test(label)) {
        data.applicant_name_masked = value
      }
      else if (/駕駛執照號碼|驾照|駕照/.test(label)) {
        data.license_number_masked = value
      }
      else if (/預約日期及時間|预约日期及时间|預約日期|预约時間|预约时间/.test(label)) {
        const dateMatch = value.match(/(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})/)
        const timeMatch = value.match(/(上午|下午)?\s*(\d{1,2}):(\d{2})/)
        if (dateMatch) {
          const [, y, m, d] = dateMatch
          const mm = String(m).padStart(2, '0')
          const dd = String(d).padStart(2, '0')
          data.appointment_date = `${y}-${mm}-${dd}`
          data.appointment_date_dmy = `${dd}-${mm}-${y}`
        }
        if (timeMatch) {
          const [, period, h, min] = timeMatch
          let hour = Number.parseInt(h)
          if (period === '下午' && hour !== 12)
            hour += 12
          if (period === '上午' && hour === 12)
            hour = 0
          data.appointment_time = `${String(hour).padStart(2, '0')}:${min}`
        }
        data.appointment_datetime_text = value
      }
      else if (/辦理地點|辦理地点|牌照事務處|办公室|办事处/.test(label)) {
        data.office = value
        data.office_display = value
      }
      else if (/電郵|邮箱|電郵地址/.test(label)) {
        data.email_masked = value
      }
      else if (/聯絡電話|联系电话|電話|电话/.test(label)) {
        data.phone_masked = value
      }
      else if (/服務|服务類別|服務類別/.test(label)) {
        data.service_type_text = value
      }
      else {
        extras.push({ label, value })
      }
    })

    if (data.appointment_date && data.appointment_time)
      data.appointment_datetime = `${data.appointment_date} ${data.appointment_time}`
    if (!data.appointment_date_dmy)
      data.appointment_date_dmy = toDMY(data.appointment_date)
    if (extras.length > 0)
      data.extras = extras

    return { success: true, data }
  }
  catch (e) {
    return { success: false, error: e instanceof Error ? e.message : String(e) }
  }
}
